﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using SaaS;
public partial class AddItems : System.Web.UI.Page
{
    XmlDocument xmldoc = new XmlDocument();
    XmlDocument xmldata = new XmlDocument();
    //set table's ID if this is an edit or data is being entered
    int tableID = -1;
    //table name
    String tableName;
    //table descrition
    String tableDescription;
    //data comment
    String dataComment;
    protected void Page_Load(object sender, EventArgs e)
    {
        string[] typeString = { "int", "double", "bool", "string" };
        if (DropDownList_type.Items.Count == 0)
            for (int i = 0; i < typeString.Length; i++)
            {
                DropDownList_type.Items.Add(typeString[i]);
            } 

        lblErr.Text = "";
        try
        {
            xmldoc.Load(Server.MapPath(@"App_Data\temp.xml"));
            if (this.TB_Items.Text.Trim() != xmldoc.DocumentElement.Name)
            {
                xmldoc = new XmlDocument();
                string temp = "<" + this.TB_Items.Text.Trim() + "><" + "/"
                    + this.TB_Items.Text.Trim() + ">";
                if (this.TB_Items.Text.Trim() == "")
                {
                    temp = "<columns></columns>";
                }

                xmldoc.LoadXml(temp);
                xmldoc.Save(Server.MapPath(@"App_Data\temp.xml"));
            }
        }
        catch (System.Exception ex)
        {
            string temp = "<" + this.TB_Items.Text.Trim() + "><" + "/"
                + this.TB_Items.Text.Trim() + ">";
            if (this.TB_Items.Text.Trim() == "")
            {
                temp = "<columns></columns>";
            }
            xmldoc.LoadXml(temp);
            xmldoc.Save(Server.MapPath(@"App_Data\temp.xml"));
        }
    }

    protected void ADD_click(object sender, EventArgs e)
    {
        lblErr.Text = "";
        if (TB_Atr.Text.Length <= 0)
        {
            lblErr.Text = "Please provide an attribute name";
            return;
        }
        xmldoc.Load(Server.MapPath(@"App_Data\temp.xml"));
        int count = xmldoc.DocumentElement.ChildNodes.Count + 1;
        //Create a new node
        XmlElement col = xmldoc.CreateElement("col");
        XmlElement xmlAtr = xmldoc.CreateElement("name");
        XmlElement xmlType = xmldoc.CreateElement("type");
        XmlElement xmlAllowNull = xmldoc.CreateElement("allownull");
        XmlElement xmlD = xmldoc.CreateElement("default");
        XmlElement columnID = xmldoc.CreateElement("columnID");
        XmlElement xmlPK = xmldoc.CreateElement("priKey");
        XmlElement xmlFK = xmldoc.CreateElement("foreign");
        XmlElement xmlFKID = xmldoc.CreateElement("foreignTableID");
        XmlElement xmlFKCol = xmldoc.CreateElement("foreignCol");

        columnID.InnerText = count.ToString();
        xmlAtr.InnerText = this.TB_Atr.Text.Trim();
        xmlType.InnerText = DropDownList_type.SelectedValue;
        xmlAllowNull.InnerText = this.rdoNullTrue.Checked ? "True" : "False";
        xmlD.InnerText = this.TB_DF.Text.Trim();
        xmlPK.InnerText = this.rdoPriKeyTrue.Checked ? "True" : "False";

        col.AppendChild(xmlAtr);
        col.AppendChild(xmlType);
        col.AppendChild(xmlAllowNull);
        col.AppendChild(xmlD);
        col.AppendChild(columnID);
        col.AppendChild(xmlPK);
        col.AppendChild(xmlFK);
        xmlFK.AppendChild(xmlFKID);
        xmlFK.AppendChild(xmlFKCol);
        xmldoc.DocumentElement.AppendChild(col);
        xmldoc.Save(Server.MapPath(@"App_Data\temp.xml"));

        TB_Atr.Text = "";
        rdoNullTrue.Checked = true;
        rdoPriKeyFalse.Checked = true;
        TB_DF.Text = "";
    }

    protected void FINISH_click(object sender, EventArgs e)
    {
        lblErr.Text = "";
        if (TB_Items.Text.Length <= 0)
        {
            lblErr.Text = "Please provide a name for the object";
            return;
        }
        else if (xmldoc.DocumentElement.ChildNodes.Count <= 0)
        {
            lblErr.Text = "Please add at least 1 attribute to the table";
            return;
        }
        xmldoc.Load(Server.MapPath(@"App_Data\temp.xml"));
        tableDescription = this.TB_DCP.Text;
        XmlDocument xmltemp = new XmlDocument();
        xmltemp.LoadXml("<columns></columns>");
        xmltemp.DocumentElement.InnerXml = xmldoc.DocumentElement.InnerXml;
        //*********************************************
        // Send to DataBase
        // 
        String colString = xmltemp.OuterXml;
        //open database connection
        MiniSaaSDB db = new MiniSaaSDB();
        db.open();
        if (db.isOpen())
        {
            System.Data.SqlClient.SqlDataReader reader;
            int count = xmldoc.DocumentElement.ChildNodes.Count;
            int id;
            int ver;
            int rows;
            tableName = this.TB_Items.Text;
            String tenantID = Session["LoginID"].ToString();
            //String tenantID = "4";
            if (tableID > 0)
            {
                //edit
                id = tableID;
                reader = db.executeQuery("SELECT MAX(Table_Version)+1 FROM META WHERE Table_ID = " + tableID.ToString());
                if (!reader.HasRows)
                    ver = 1;
                else
                {
                    reader.Read();
                    ver = (int)reader[0];
                }
            }
            else
            {
                //create new
                ver = 1;
                reader = db.executeQuery("SELECT MAX(Table_ID)+1 FROM META");
                if (!reader.HasRows)
                    id = 1;
                else
                {
                    reader.Read();
                    id = (int)reader[0];
                }
            }
            reader.Close();
            String query;
            query = "INSERT INTO META (Table_ID, Table_Version, Login_ID, " +
                "Table_Name, Table_Columns_Count, Table_Columns, Table_Description) " +
                "VALUES (" + id.ToString() + ", " + ver.ToString() + ", " + tenantID.ToString() + ", '" + tableName + "', " +
                count.ToString() + ", '" + colString + "', ";
            if (tableDescription != null && tableDescription.Length > 0)
                query = query + "'" + tableDescription + "');";
            else
                query = query + "NULL);";
            rows = db.executeNonQuery(query);
            if (rows <= 0)
            {
                //No rows affected
                db.close();
                return;
            }
            db.close();

            TB_Items.Text = "";
            TB_DCP.Text = "";
        }
        else
        {
            //Error opening DB
            lblErr.Text = "Error opening database.";
            return;
        }
    }
    protected void DropDownList_type_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
}